<template>
  <div v-loading="loading" class="detail-container clearfix">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-width="80px" label-position="top">
      <el-row>
        <el-col class="baseForm" :md="8">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="postForm.username" :disabled="disabled" placeholder="用户名" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="postForm.nickname" placeholder="昵称" />
          </el-form-item>
          <el-form-item label="所属角色" prop="role_id">
            <el-select v-model="postForm.role_id" style="width:100%" placeholder="请选择">
              <el-option
                v-for="op in roleList"
                :key="op.id"
                :label="op.title"
                :value="op.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="postForm.password" placeholder="密码，新增时必填，编辑时可选(留空保留原密码，填写即修改为新密码)" />
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="postForm.status">
              <el-radio-button label="1">正常</el-radio-button>
              <el-radio-button label="0">禁用</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col class="mycard-wrap" :md="14">
          <el-form-item label="渠道权限" label-width="100px" label-position="right">
            <div class="mycard">
              <div class="mycard-body">
                <el-checkbox v-model="channelAll" class="platform" @change="allChannelToggle()">全渠道</el-checkbox>
                <div>
                  <el-checkbox
                    v-for="(channel,key) in channelPackageList"
                    :key="key"
                    v-model="postForm.cpid"
                    class="platform"
                    :label="channel.cpid"
                    :disabled="channelDisabled"
                  >{{ channel.cpname }}</el-checkbox>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="服务器大区权限" label-width="100px" label-position="right">
            <div class="mycard">
              <div class="mycard-body">
                <el-checkbox v-model="regionAll" class="platform" @change="allRegionToggle()">全部大区</el-checkbox>
                <div>
                  <el-checkbox
                    v-for="(region,key) in serverRegionList"
                    :key="key"
                    v-model="postForm.region"
                    class="platform"
                    :label="region.id"
                    :disabled="regionDisabled"
                  >{{ region.name }}</el-checkbox>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-button class="mt-30" type="primary" @click="confirmSubmit()">确 定</el-button>
      <el-button v-if="!isEdit" class="mt-30" type="info" @click="resetForm()">重 置</el-button>
    </el-form>
  </div>
</template>

<script>

import { fetchUser, handleUser } from '@/api/user'
import { getUserRoles } from '@/api/role'
import { getChannelPackageList, getServerRegionList } from '@/api/ops'

const defaultItem = {
  id: '',
  username: '',
  nickname: '',
  cpid: [],
  region: [],
  role_id: '',
  password: '',
  status: 1
}
export default {
  name: 'UserDetail',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6 && !this.isEdit) {
        callback(new Error('密码不能少于6个字符！！'))
      } else {
        callback()
      }
    }
    return {
      roleList: [], // 所有用户角色列表
      serverRegionList: [],
      channelPackageList: [],
      postForm: Object.assign({}, defaultItem),
      loading: false,
      disabled: false,
      channelAll: true,
      regionAll: true,
      channelDisabled: true,
      regionDisabled: true,
      rules: {
        username: [{ required: true, message: '请填写用户名', trigger: 'blur' }],
        role_id: [{ required: true, message: '请选择角色', trigger: 'change' }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      tempRoute: {}
    }
  },
  watch: {
  },
  created() {
    this.init()
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    // 重置数据
    resetForm() {
      this.postForm = {
        id: '',
        username: '',
        nickname: '',
        role_id: '',
        password: '',
        email: '',
        status: 1
      }
    },

    init() {
      this.loading = true
      this.getUserRoles()
      this.getServerRegion()
      this.getChannelPackage()
      this.$nextTick(() => {
        if (this.isEdit) {
          this.disabled = true
          const id = this.$route.params && this.$route.params.id
          this.fetchData(id)
        }
        this.loading = false
      })
    },

    async getUserRoles() {
      const res = await getUserRoles()
      this.roleList = res.data
    },
    async getServerRegion() {
      const res = await getServerRegionList()
      this.serverRegionList = res.data
    },
    async getChannelPackage() {
      const res = await getChannelPackageList()
      this.channelPackageList = res.data.items
    },
    async fetchData(id) {
      fetchUser(id).then(response => {
        const data = response.data
        if (data.my_channels === 'all') {
          this.channelAll = true
          data.my_channels = []
        } else {
          this.channelAll = false
          this.channelDisabled = false
        }
        if (data.my_regions === 'all') {
          this.regionAll = true
          data.my_regions = []
        } else {
          this.regionAll = false
          this.regionDisabled = false
        }
        this.$nextTick(() => {
          this.postForm = {
            id: data.id,
            username: data.username,
            nickname: data.nickname,
            role_id: data.role_id,
            password: '',
            cpid: data.my_channels,
            region: data.my_regions,
            status: data.status
          }
          // 设置标签栏名名称
          this.setTagsViewTitle()
        })
      }).catch(err => {
        console.log(err)
      })
    },
    allChannelToggle() {
      this.postForm.cpid = []
      if (this.channelDisabled === true) {
        this.channelDisabled = false
      } else {
        this.channelDisabled = true
      }
    },
    allRegionToggle() {
      this.postForm.region = []
      if (this.regionDisabled === true) {
        this.regionDisabled = false
      } else {
        this.regionDisabled = true
      }
    },
    setTagsViewTitle() {
      const title = '编辑 - ' + this.postForm.username
      const route = Object.assign({}, this.tempRoute, { title: `${title}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    confirmSubmit() {
      this.$refs['postForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          handleUser(this.postForm).then(response => {
            this.loading = false
            this.$message({
              type: 'success',
              message: response.message
            })
          }).catch(err => {
            this.loading = false
            this.$message.error(err)
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-container {
    padding: 30px;

    .baseForm{
      border-right: 1px solid #EBEEF5;
      padding-right: 1.4em;
    }
    .mycard-wrap {
        /*
        max-height: 700px;
        overflow: auto;
        */
        padding-left: 1.4em;

        .mycard {
          -webkit-box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
          box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
          border-radius: 4px;
          border: 1px solid #EBEEF5;
          background-color: #FFF;
          color: #303133;
          -webkit-transition: .3s;
          transition: .3s;
          margin-bottom: 20px;

          .mycard-header {
              padding: 10px 15px;
              border-bottom: 1px solid #EBEEF5;
              span {
                  font-size: 14px;
              }
          }
          .mycard-body {
              padding: 10px 15px;
              font-size: 12px;
              max-height: 400px;
              overflow: auto;

              .platform {
                width: 138px;
                margin-right: 10px;
              }
          }
      }
    }

}
</style>
